package main

import (
	"fmt"
	"github.com/gorilla/sessions"
	"net/http"
)

var (
	key   = []byte("super-secret-key")
	store = sessions.NewCookieStore(key)
)

func login(writer http.ResponseWriter, request *http.Request) {
	session, _ := store.Get(request, "cookie-name")
	//TODO 处理认证
	if "admin" == request.URL.Query()["name"][0] {
		session.Values["authenticated"] = true
		session.Save(request, writer)
	}
}
func logout(writer http.ResponseWriter, request *http.Request) {
	session, _ := store.Get(request, "cookie-name")
	//
	session.Values["authenticated"] = false
	session.Save(request, writer)
}
func secret(writer http.ResponseWriter, request *http.Request) {
	session, _ := store.Get(request, "cookie-name")
	if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
		http.Error(writer, "Forbidden", http.StatusForbidden)
	} else {
		fmt.Fprintf(writer, "hello world")
	}
}
func main() {
	http.HandleFunc("/secret", secret)
	http.HandleFunc("/login", login)
	http.HandleFunc("/logout", logout)
	http.ListenAndServe(":8989", nil)
}
